/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cbsnserverparte;

import java.io.*;

/**
 *
 * @author Craig Butler (5668670)
 * @author Stephen Norman (616000X)
 */
final class Reader implements Runnable
{   
    /* Private Variables */
    private boolean _hasData;
    private DataInputStream _reader;
    private byte[] _data;
    
    /**
     * Constructor for Reader class
     * 
     * @param reader The DataInputStream reader to read data from the relay
     */
    public Reader(DataInputStream reader)
    {
        // Set _reader to the incoming reader
        _reader = reader;
        _hasData = false;
    };
    
    public void run()
    {
        // Start Reading
        readData();
    }

    /**
     * Reads data from the socket indefinitely
     */
    private void readData()
    {   
        // Create a new array to store incoming data
        _data = new byte[1460];
        
        // If something goes wrong we should know about it
        try
        {
            while (true)
            {
                // Read 1460 bytes of incoming data
                _reader.readFully(_data);
                
                // Inform the user
                System.out.println(Util.getTime() + "Data from client received and ready for processing...");
                
                // Once it has been read
                // we need to tell the protocol
                // that we have some data for it
                _hasData = true;
            }
        }
        catch (Exception ex)
        {
            System.out.println(Util.getTime() + "Read Error: " + ex.getMessage());
        }
    }
    
    public boolean isDataAvailable()
    {
        return _hasData;
    }
    
    /**
     * Gets the data we have receieved
     * 
     * @return The data array of the packet
     */
    public byte[] getData()
    {        
        // We no longer have data available
        _hasData = false;
        
        // Return the current array of data
        return _data;
    }
}
